import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_base_package/x3_base_package.dart';
import 'package:x3_business_core/business_customer/less_components/business_customer_details_dynamic_interact_content.dart';

class BusinessCustomerDetailsDynamicList extends StatefulWidget {
  final String service;

  final Widget header;

  final BaseRefreshController controller;

  final Widget Function(Widget) decorator;

  const BusinessCustomerDetailsDynamicList(
      {Key key,
      @required this.controller,
      @required this.service,
      this.header,
      this.decorator})
      : assert(controller != null),
        assert(service != null),
        super(key: key);

  @override
  _BusinessCustomerDetailsDynamicListState createState() =>
      _BusinessCustomerDetailsDynamicListState();
}

class _BusinessCustomerDetailsDynamicListState
    extends State<BusinessCustomerDetailsDynamicList>
    with AutomaticKeepAliveClientMixin {
  /// 数据列表
  List<dynamic> _dataList = [];

  /// 当前是第几页
  int _pageIndex = 1;

  /// 每页显示多少条数
  int _pageSize = 15;

  /// 加载状态
  LoadingStatusEnum loadingStatus;

  @override
  void initState() {
    /// 初始化数据
    loadingStatus = LoadingStatusEnum.Loading;
    this._getDataList();

    /// 监听刷新数据
    widget.controller.addListener(() {
      widget.controller.isSearch ? this._onRefresh() : this._onLoadData();
    });
    super.initState();
  }

  @override
  void dispose() {
    widget.controller.dispose();
    super.dispose();
  }

  /// 加载数据
  void _onLoadData() {
    if (this.loadingStatus == LoadingStatusEnum.LoadingComplete) {
      this._pageIndex++;
      this._getDataList();
    }
  }

  /// 刷新
  void _onRefresh() {
    this._pageIndex = 1;
    this._dataList = [];
    this._getDataList();
  }

  /// 获取数据
  Future<BaseHttpResultModel> _getDataList() async {
    setState(() {
      loadingStatus = LoadingStatusEnum.Loading;
    });
    Map<String, dynamic> pageParams = {
      'pageIndex': this._pageIndex,
      'pageSize': _pageSize
    };
    Map<String, dynamic> params = {};
    params.addAll(widget.controller.params);
    params.addAll(pageParams);
    BaseHttpResultModel result =
        await dioUtil.fetch(widget.service, params: params);
    if (result.data is List) {
      List<dynamic> listData = result.data;
      setState(() {
        this._dataList.addAll(listData);
        listData.length < _pageSize
            ? loadingStatus = LoadingStatusEnum.NoMore
            : loadingStatus = LoadingStatusEnum.LoadingComplete;
      });
    } else {
      setState(() {
        loadingStatus = LoadingStatusEnum.NoMore;
      });
    }
    return result;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return NotificationListener(
      child: RefreshIndicator(
        onRefresh: () async {
          this._onRefresh();
        },
        child: ListView(
          physics: AlwaysScrollableScrollPhysics(),
          shrinkWrap: true,
          children: [
            widget.header ?? SizedBox(),
            _buildContentList(),
          ],
        ),
      ),
      onNotification: _onScrollNotification,
    );
  }

  Widget _buildContentList() {
    if (this._dataList.length == 0 &&
        this.loadingStatus == LoadingStatusEnum.Loading)
      return BaseLoadingComponent();
    Widget _content = ListView(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      children: [
        _buildContent(),
        _buildLoadStatus(),
      ],
    );
    if (widget.decorator != null) _content = widget.decorator(_content);
    return _content;
  }

  /// 创建内容
  Widget _buildContent() {
    if (this._dataList.length > 0) {
      List<BaseTimeLineStep> steps = _dataList.map((e) {
        String _date = BaseTransformUtil.stringToDate(e['createDate']);
        String _time = BaseTransformUtil.stringToTimeStamp(e['createDate'],
            isNeedShowSecond: false);
        return BaseTimeLineStep(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [Text(e['interactTypeName'] ?? '')],
            ),
            stepWidget: BaseImageComponent(imageUrl: e['iconImg']),
            content: BusinessCustomerDetailsDynamicInteractContent(
                interactContent: e['interactContent'] ?? '',
                interactType: e['interactType']),
            subtitle: DefaultTextStyle(
              style:
                  Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 11),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [Text(_date), Text(_time)]),
            ));
      }).toList();
      return BaseTimeLineStepper(size: 24, steps: steps);
    }
    return BaseEmptyComponent();
  }

  /// 状态部件
  Widget _buildLoadStatus() {
    Widget child;
    switch (this.loadingStatus) {
      case LoadingStatusEnum.Loading:
        child = BaseBottomLoadingComponent();
        break;
      case LoadingStatusEnum.LoadingComplete:
        child = SizedBox();
        break;
      case LoadingStatusEnum.NoMore:
        if (this._dataList.length == 0) {
          child = SizedBox();
        } else {
          child = Container(
              width: double.infinity,
              alignment: Alignment.center,
              child: BaseNoMoreComponent());
        }
        break;
      default:
    }
    return child;
  }

  bool _onScrollNotification(ScrollNotification scrollInfo) {
    /// 当前滚动的高度
    double currentScrollPixels = scrollInfo.metrics.pixels;

    /// 最大可滚动的高度 ( 如果当前的最大可滚动高度为0 则表明当前ListView没有占满当前屏幕 )
    double maxScrollPixels = scrollInfo.metrics.maxScrollExtent;
    if (currentScrollPixels == maxScrollPixels) this._onLoadData();
    return true;
  }

  @override
  bool get wantKeepAlive => true;
}
